package com.scientificInfo.interceptor;

import com.scientificInfo.exception.GlobalException;
import com.scientificInfo.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o){
        //获取header中的token以及对应的claims信息
        String token = request.getHeader("token");

        //是否通过
        Boolean isAllowPass = true;

        //如果token信息为空
        if(token == null){
            isAllowPass = false;
        }else{
            //获取到token中的信息 并看是否过期
            if(jwtUtils.getClaimByToken(token) == null){
                throw new GlobalException("您好，您的用户信息已过期！请重新登录。");
            }
        }
        return isAllowPass;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
